package com.jslex.adapter;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Set;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Decompiler;
import org.mozilla.javascript.Script;

/**
 * Class incorporates a bunch of the functionality need to work with the Rhino engine
 * adaption used by jsLex.  It contains a bunch of utility methods.
 * @author bbuffone
 *
 */
public class JsLexUtil {
	
	public JsLexUtil(){
		
	}

	public void resetDecompiler(){
		Decompiler.resetDecompiler();
	}

	public Context contextEnter(){
		return Context.enter();
	}
	
	public Set getCounterFunctionKeys(){
		return Decompiler.COUNTR_TO_FUNCTION_NAME_HASH_MAP.keySet();
	}
	
	public void clearCounterFunctionKeys(){
		Decompiler.COUNTR_TO_FUNCTION_NAME_HASH_MAP.clear();
	}
	
	public String getFunctionName(Integer index){
		return (String)Decompiler.COUNTR_TO_FUNCTION_NAME_HASH_MAP.get(index);
	}
	
	public void contextExit(){
		Context.enter();
	}
	
	/**
     * Compress the file content using the Dojo compression
     * 
     * @param fileContent
     * @return
     */
    public String compressFile(File sourceFile, Integer eol, Integer profileInjectionValue, Integer compressNames) throws IOException{
    	Context cx = Context.enter();
   		String 	fileContent = null;
   		
    	FileReader	fileReader = new FileReader(sourceFile);
 	    Script		script = cx.compileReader(fileReader, sourceFile.getName(), 0, null);
	    fileReader.close();
 	    
	    fileContent = cx.compressScript(script, 1, eol.intValue(), profileInjectionValue.intValue(), compressNames.intValue());
   	
    	Context.exit();
    	return fileContent;
    }

}
